<template>
  <div class="page">
    <div class="page-container">
      <van-nav-bar :title="$route.meta.title">
        <template #right>
          <van-icon name="plus" size="18" @click="toAddGroup"/>
        </template>
      </van-nav-bar>
      <van-dropdown-menu active-color="#1989fa">
        <van-dropdown-item v-model="deviceId" :options="devices" @change="loadGroups" />
        <van-dropdown-item v-model="value2" :options="option2" />
      </van-dropdown-menu>
      <van-row v-show="groupsLoading" style="margin-top: 20px;">
        <van-col span="24" align="center">
          <van-loading size="24px">加载中...</van-loading>
          </van-col>
      </van-row>
      <van-swipe-cell v-for="group in groups" :key="group.id" :before-close="beforeClose" >
        <van-cell icon="circle" :title="group.name" @click="toGroupOrders(group)"/>
        <template #right>
          <van-button square type="info" text="编辑" @click="toAddGroup(group)"/>
          <van-button square type="danger" text="删除" @click="toDelGroup(group)"/>
        </template>
      </van-swipe-cell>
    </div>
    <van-popup v-model="addGroupShow" round position="bottom">
      <van-form @submit="saveGroup" style="margin: 10px">
        <van-field
          v-model="groupForm.name"
          name="组名"
          label="组名"
          placeholder="请填写组名"
          :rules="[{ required: true, message: '请填写组名' }]"
          clearable
        />
        <div style="margin: 16px;">
          <van-button :loading="groupSaving" round block type="info" native-type="submit" loading-type="spinner">提交</van-button>
        </div>
      </van-form>
    </van-popup>
    <tab-bar :active-index="0"/>
    <van-overlay :show="loadingLayer">
        <div class="loading-wrapper" @click.stop>
            <van-loading size="24px" color="#0094ff" vertical >{{ loadingLayerText }}</van-loading>
        </div>
    </van-overlay>
  </div>
</template>

<script>
import { Dialog } from 'vant';
import { Notify } from 'vant';
export default {
  data: function () {
    return {
      // enter some data
      deviceId: 0,
      value2: 0,
      devices: [],
      option2: [
        { text: '全部', value: 0 },
        { text: '房间1', value: 1 },
        { text: '房间2', value: 2 },
        { text: '房间3', value: 3 },
      ],
      groups: [], groupsLoading: false,
      addGroupShow: false, groupForm: {}, groupSaving: false,
      loadingLayer: false, loadingLayerText: '...',
    }
  },
  mounted() {
    this.loadDevices()
  },
  methods: {
    // put some function here
    loadDevices() {
      this.$api.request("/device/options",{
      }).then(response=>{
        if (response.code === 1) {
          this.devices = response.data.map(d => {
            return {
              text: d.ssid,
              value: d.id
            }
          })
          this.deviceId = this.devices[0].value
          this.loadGroups()
        } else {
          Notify({ type: 'warning', message: `查询失败：${response.message}` });
        }
      }).catch(e=>{
          Notify({ type: 'danger', message: '网络请求失败' });
      })
    },
    loadGroups() {
      this.groups = []
      this.groupsLoading = true
      this.$api.request("/group/list",{
        params: {
          deviceId: this.deviceId
        }
      }).then(response=>{
        if (response.code === 1) {
          this.groups = response.data
        } else {
          Notify({ type: 'warning', message: `查询失败：${response.message}` });
        }
      }).catch(e=>{
          Notify({ type: 'danger', message: '网络请求失败' });
      }).then(()=>{
          this.groupsLoading = false
      })
    },
    // position 为关闭时点击的位置
    // instance 为对应的 SwipeCell 实例
    beforeClose({ position, instance }) {
      // console.log(position);
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close();
          break;
        case 'right':
          instance.close();
          break;
      }
    },
    toAddGroup(group) {
      if (group && group.id) {
        this.groupForm = {
          ...group
        }
      } else {
        this.groupForm = {
          deviceId: this.deviceId
        }
      }
      this.addGroupShow = true
    },
    saveGroup() {
      this.groupSaving = true
      this.$api.request('/group/save',{
        method: 'POST',
        data: this.groupForm
      }).then(response=>{
        if (response.code === 1) {
          this.addGroupShow = false
          this.groupForm = {}
          this.loadGroups()
          Notify({ type: 'success', message: '保存成功', duration: 1500 });
        } else {
          Notify({ type: 'warning', message: `保存失败：${response.message}` });
        }
      }).catch(e=>{
        Notify({ type: 'warning', message: `网络请求失败：${e.message}` });
      }).then(()=>{
        this.groupSaving = false
      })
    },
    toDelGroup(group) {
      Dialog.confirm({
        // title: '标题',
        message: '确认删除该分组及分组下的指令吗?',
      })
        .then(() => {
          // on confirm
          this.loadingLayer = true
          this.loadingLayerText = '删除中...'
          this.$api.request("/group/delete/" + group.id,{
          }).then(response=>{
            if (response.code === 1) {
              Notify({ type: 'success', message: '已删除', duration: 1500 });
              this.loadGroups()
            } else {
              Notify({ type: 'warning', message: `删除失败：${response.message}` });
            }
          }).catch(e=>{
              Notify({ type: 'danger', message: '网络请求失败' });
          }).then(()=>{
              this.loadingLayer = false
          })
        })
        .catch(() => {
          // on cancel
        });
    },
    toGroupOrders(group) {
      this.$router.push({path:'/order', query: group})
    },
  }
}
</script>
